/*
 * @Description: 真实性格式设置弹窗
 * @Author: Rfan
 * @Date: 2022-10-10 20:45:23
 * @LastEditTime: 2022-10-22 17:13:57
 */

import { useEffect } from 'react';
import { Checkbox, Form, Input, Space } from 'antd';
import classnames from 'classnames/bind';
import { selectItemByKey } from '@/utils/list';
import { EnumCheckContentType, EnumFieldCheckType } from '../../../../../../../../dictionaries';
import type { Callbacks } from 'rc-field-form/lib/interface';
import styles from '../../../../../styles/entryPanes.module.scss';

const cx = classnames.bind(styles);

interface IFieldLengthProps {
  data: any;
  onChange: any;
}

const FieldLength = (props: IFieldLengthProps) => {
  const { data, onChange } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    if (data?.rules) {
      const lengthData = selectItemByKey(EnumFieldCheckType.Length, data.rules, 'ruleType');
      if (lengthData && lengthData.rule) {
        form.setFieldsValue({ ...lengthData.rule, ruleValid: lengthData.ruleValid });
      }
    }
  }, [data]);

  /**
   * @description: 表单变动触发
   * @param {*} _changeVal 变化的值
   * @param {*} values 变化后整个表单的值
   */
  const changeFormFunc: Callbacks['onValuesChange'] = (_changeVal, values) => {
    const fieldRuleType = EnumFieldCheckType.Length;
    const rule = { ...values, contentType: EnumCheckContentType.Regular };
    delete rule.ruleValid;

    const editLengthObj = {
      ruleType: fieldRuleType,
      ruleValid: values.ruleValid,
      rule
    };

    onChange(data.key, fieldRuleType, editLengthObj);
  };

  return (
    <Form
      form={form}
      className={cx('field-length')}
      layout="inline"
      size="small"
      onValuesChange={changeFormFunc}
    >
      <Space size="small">
        <Form.Item name="ruleValid" valuePropName="checked">
          <Checkbox />
        </Form.Item>
        <Form.Item name="content">
          <Input className={cx('length--content')} />
        </Form.Item>
      </Space>
    </Form>
  );
};

export default FieldLength;
